"use client";
import { Create, useForm } from "@refinedev/antd";
import { useParsed } from "@refinedev/core";
import { Form, Input, InputNumber, Select, TreeSelect, Upload, Button, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { useState, useEffect } from "react";
import { uploadImage } from "@common/api/upload_action";
import { getCategoryOptions } from "@common/api/category_action";

export default function NewsCreate() {
  const { id } = useParsed();
  const { formProps, saveButtonProps } = useForm({
    resource: "project/news",
    id: id
  });
  const [imageUrl, setImageUrl] = useState<string>('');
  const [uploading, setUploading] = useState(false);
  const [categoryTreeData, setCategoryTreeData] = useState<any[]>([]);

  // 获取分类选项
  useEffect(() => {
    getCategoryOptions().then((res: any) => {
      if (res.code === 200) {
        setCategoryTreeData(res.data || []);
      }
    }).catch((error) => {
      console.error('获取分类选项失败:', error);
    });
  }, []);

  return (
    <Create saveButtonProps={saveButtonProps}>
      <Form {...formProps} layout="vertical">
        <Form.Item name="category_alias" label="分类别名"> 
          <TreeSelect
            placeholder="请选择分类"
            allowClear
            treeData={categoryTreeData}
            fieldNames={{ label: 'label', value: 'value', children: 'children' }}
            treeDefaultExpandAll
            loading={categoryTreeData.length === 0}
            style={{ width: '100%' }}
            showSearch
            treeNodeFilterProp="label"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          />
        </Form.Item>
        <Form.Item 
          name="alias" 
          label="别名" 
          rules={[
            { required: true, message: '请输入别名' },
            { 
              pattern: /^[a-zA-Z0-9_-]+$/, 
              message: '别名只能包含字母、数字、下划线和连字符' 
            }
          ]}
          extra="别名必须唯一，用于标识新闻"
        > 
          <Input placeholder="请输入唯一的别名" /> 
        </Form.Item>
        <Form.Item name="url" label="URL"> 
          <Input /> 
        </Form.Item>
        <Form.Item name="image" label="图片">
          <div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
            <Upload
              name="image"
              showUploadList={false}
              beforeUpload={(file) => {
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                  message.error('只能上传图片文件!');
                  return false;
                }
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isLt5M) {
                  message.error('图片大小不能超过5MB!');
                  return false;
                }
                return false; // 阻止自动上传
              }}
              onChange={(info) => {
                if (info.file.status === 'removed') {
                  setImageUrl('');
                  formProps.form?.setFieldsValue({ image: '' });
                }
              }}
            >
              <Button 
                icon={<UploadOutlined />} 
                loading={uploading}
                                onClick={async (e) => {
                  e.preventDefault();
                  e.stopPropagation(); // 阻止事件冒泡
                  const input = document.createElement('input');
                  input.type = 'file';
                  input.accept = 'image/*';
                  input.onchange = async (event) => {
                    const file = (event.target as HTMLInputElement).files?.[0];
                    if (file) {
                      setUploading(true);
                      try {
                        const response: any = await uploadImage(file);
                        console.log('Upload response:', response); // 调试日志
                        if (response.code === 200) {
                          const url = response.data.url;
                          setImageUrl(url);
                          formProps.form?.setFieldsValue({ image: url });
                          message.success('图片上传成功!');
                        } else {
                          message.error(response.msg || '上传失败');
                        }
                      } catch (error) {
                        console.log('Upload error:', error);
                        message.error('上传失败');
                      } finally {
                        setUploading(false);
                      }
                    }
                  };
                  input.click();
                }}
              >
                上传图片
              </Button>
            </Upload>
            <Input 
              placeholder="或直接输入图片URL" 
              value={imageUrl}
              onChange={(e) => {
                setImageUrl(e.target.value);
                formProps.form?.setFieldsValue({ image: e.target.value });
              }}
            />
          </div>
          {imageUrl && (
            <div style={{ marginTop: '8px' }}>
              <img 
                src={imageUrl} 
                alt="预览" 
                style={{ 
                  maxWidth: '200px', 
                  maxHeight: '200px', 
                  objectFit: 'cover',
                  borderRadius: '4px',
                  border: '1px solid #d9d9d9'
                }} 
              />
            </div>
          )}
        </Form.Item>
        <Form.Item name="view" label="浏览次数"> 
          <InputNumber style={{ width: '100%' }} /> 
        </Form.Item>
        <Form.Item name="sort" label="排序"> 
          <InputNumber style={{ width: '100%' }} /> 
        </Form.Item>
        <Form.Item name="recommend" label="推荐"> 
          <Select
            options={[
              { label: '否', value: 0 },
              { label: '是', value: 1 }
            ]}
          />
        </Form.Item>
        <Form.Item name="status" label="状态"> 
          <Select
            options={[
              { label: '禁用', value: 0 },
              { label: '启用', value: 1 }
            ]}
          />
        </Form.Item>
      </Form>
    </Create>
  );
} 